package gui

import (
	"context"
	"embed"
	"gitee.com/xgh2012/wails_common/wails_apps"
	"gitee.com/xgh2012/wails_common/wails_core"
	"gitee.com/xgh2012/wails_common/wails_core/systems"
	"gitee.com/xgh2012/wails_common/wails_utils"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/menu"
	"github.com/wailsapp/wails/v2/pkg/menu/keys"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

var (
	AppRegister = &Register{}
	AppDialog   = &Dialog{}
)

// RunApp 运行主界面
func RunApp(assets embed.FS) {
	// Create an instance of the app structure
	app := NewApp()

	// Create application with options
	if err := wails.Run(&options.App{
		Title:  wails_apps.SoftTitle + " " + wails_apps.Version,
		Width:  850,
		Height: 780,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		Menu: createMenu(),
		//BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup: app.startup,
		Bind: []any{
			app,
			AppRegister,
			AppDialog,
		},
	}); err != nil {
		println("Error:", err.Error())
	}
}

// App struct
type App struct {
	Ctx context.Context
}

// NewApp creates a new application struct
func NewApp() *App {
	return &App{}
}

// Startup is called when the app starts. The context is saved,
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.Ctx = ctx
	systems.Context = ctx
}

type RegisterWindowOpen struct {
	IsRegistered bool
	MachineCode  string
}

func createMenu() *menu.Menu {
	appMenu := menu.NewMenu()
	fileMenu := appMenu.AddSubmenu("文件")
	fileMenu.AddText("打开", keys.CmdOrCtrl("o"), func(_ *menu.CallbackData) {

	})
	fileMenu.AddSeparator()
	fileMenu.AddText("退出", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
		runtime.Quit(systems.Context)
	})

	settingMenu := appMenu.AddSubmenu("设置")
	settingMenu.AddText("注册", keys.Control("z"), func(_ *menu.CallbackData) {
		tmp := &RegisterWindowOpen{
			IsRegistered: systems.IsRegistered,
		}
		var result *wails_core.Result
		if tmp.IsRegistered {
			result = wails_core.Success(tmp)
		} else {
			soft, err := wails_utils.GetSoftInfo(wails_apps.SoftName)
			if err == nil {
				tmp.MachineCode = wails_utils.GetJwtToken(soft + wails_apps.SoftName)
				result = wails_core.Success(tmp)
			} else {
				result = wails_core.Wrong(999, err.Error(), nil)
			}
		}

		runtime.EventsEmit(systems.Context, "RegisterWindowOpen", result)
	})

	//settingMenu.AddSeparator()
	//settingMenu.AddText("退出", nil, func(_ *menu.CallbackData) {
	//	runtime.Quit(systems.Context)
	//})

	return appMenu
}
